package cn.wolfcode.p2p.base.util;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by wolfcode on 2018/7/22.
 */
public class UserContext {
	public static final String USER_IN_SESSION = "loginInfo";

	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	/**
	 * 在session中设置当前用户
	 * 
	 * @param loginInfo
	 */
	public static void setCurrent(LoginInfo loginInfo) {
		getRequest().getSession().setAttribute(USER_IN_SESSION, loginInfo);
	}

	/**
	 * 从session中获取当前用户
	 * 
	 * @return
	 */
	public static LoginInfo getCurrent() {
		return (LoginInfo) getRequest().getSession().getAttribute(USER_IN_SESSION);
	}

	/**
	 * 获取客户端的ip
	 * 
	 * @return
	 */
	public static String getIp() {
		return getRequest().getRemoteAddr();
	}
}
